package com.studyroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.studyroom.dto.SearchDTO;
import com.studyroom.entity.Order;
import com.studyroom.entity.OrderItem;
import com.studyroom.entity.Snack;
import com.studyroom.entity.User;
import com.studyroom.exception.ServiceException;
import com.studyroom.mapper.OrderMapper;
import com.studyroom.mapper.UserMapper;
import com.studyroom.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private UserService userService;
    
    @Autowired
    private SnackService snackService;
    
    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean isAdmin(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);
        return user != null && user.getIsAdmin() == 1;
    }

    @Override
    public IPage<Order> search(SearchDTO params) {
        Page<Order> page = new Page<>(params.getCurrent(), params.getSize());
        
        // 手动处理日期时间参数
        LocalDateTime startDateTime = null;
        LocalDateTime endDateTime = null;
        
        try {
            if (params.getStartTime() != null && !params.getStartTime().isEmpty()) {
                startDateTime = LocalDateTime.parse(params.getStartTime(), 
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            
            if (params.getEndTime() != null && !params.getEndTime().isEmpty()) {
                endDateTime = LocalDateTime.parse(params.getEndTime(), 
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        } catch (Exception e) {
            throw new ServiceException("日期时间格式不正确: " + e.getMessage());
        }
        
        // 传递参数
        return baseMapper.searchOrders(
            page, 
            params.getKeyword(), 
            params.getStatus(), 
            startDateTime, 
            endDateTime, 
            params.getSortField(), 
            params.getSortOrder()
        );
    }

    @Override
    public List<Order> getLatestOrders(String username) {
        if (isAdmin(username)) {
            return baseMapper.selectLatestOrders();
        } else {
            // 如果不是管理员，只返回自己的最新订单
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getUserId, getUserId(username))
                  .orderByDesc(Order::getCreatedAt)
                  .last("LIMIT 10");  // 限制返回最新的10条
            return list(wrapper);
        }
    }

    @Override
    public Order getOrderDetail(Long orderId) {
        Map<String, Object> result = baseMapper.getOrderDetail(orderId);
        if (result == null) {
            return null;
        }
        
        Order order = new Order();
        // 设置基本属性
        order.setId(((Number)result.get("id")).longValue());
        order.setUserId(((Number)result.get("user_id")).longValue());
        order.setTotalAmount(new BigDecimal(result.get("total_amount").toString()));
        order.setStatus((Integer)result.get("status"));
        order.setDeliveryLocation((String)result.get("delivery_location"));
        
        // 处理日期时间
        if (result.get("delivery_time") != null) {
            order.setDeliveryTime(LocalDateTime.parse(result.get("delivery_time").toString(), formatter));
        }
        if (result.get("created_at") != null) {
            order.setCreatedAt(LocalDateTime.parse(result.get("created_at").toString(), formatter));
        }
        if (result.get("updated_at") != null) {
            order.setUpdatedAt(LocalDateTime.parse(result.get("updated_at").toString(), formatter));
        }
        
        // 处理订单项
        String orderItems = (String)result.get("orderItems");
        if (orderItems != null && !orderItems.isEmpty()) {
            List<OrderItem> items = new ArrayList<>();
            String[] itemArray = orderItems.split(",");
            for (int i = 0; i < itemArray.length; i += 4) {
                OrderItem item = new OrderItem();
                item.setId(Long.parseLong(itemArray[i]));
                item.setSnackName(itemArray[i + 1]);
                item.setQuantity(Integer.parseInt(itemArray[i + 2]));
                item.setPrice(new BigDecimal(itemArray[i + 3]));
                items.add(item);
            }
            order.setOrderItems(items);
        }
        
        return order;
    }

    @Override
    public boolean updateOrderStatus(Long orderId, Integer status) {
        Order order = getById(orderId);
        if (order == null) {
            return false;
        }
        order.setStatus(status);
        return updateById(order);
    }

    @Override
    @Transactional
    public void cancelOrder(String username, Long orderId) {
        // 1. 获取用户信息
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 2. 获取订单信息
        Order order = getById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }

        // 3. 验证是否是当前用户的订单
        if (!order.getUserId().equals(user.getId())) {
            throw new ServiceException("无权操作此订单");
        }

        // 4. 检查订单状态是否可取消
        if (order.getStatus() != 0) {  // 只有待支付状态可以取消
            throw new ServiceException("当前状态不可取消");
        }

        // 5. 取消订单
        order.setStatus(4);  // 设置为已取消
        order.setUpdatedAt(LocalDateTime.now());
        updateById(order);

        // 6. 恢复库存
        List<OrderItem> items = orderItemService.getByOrderId(orderId);
        for (OrderItem item : items) {
            Snack snack = snackService.getById(item.getSnackId());
            snack.setStock(snack.getStock() + item.getQuantity());
            snackService.updateById(snack);
        }
    }

    @Override
    @Transactional
    public void createOrder(String username, List<OrderItem> items, String deliveryLocation, LocalDateTime deliveryTime) {
        // 1. 获取用户信息
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 2. 创建订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setDeliveryLocation(deliveryLocation);
        order.setDeliveryTime(deliveryTime);
        order.setStatus(0);  // 设置为待支付
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());

        // 3. 计算总金额并检查库存
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItem item : items) {
            Snack snack = snackService.getById(item.getSnackId());
            if (snack == null || snack.getStatus() != 1) {
                throw new ServiceException("商品不可购买：" + item.getSnackId());
            }
            if (snack.getStock() < item.getQuantity()) {
                throw new ServiceException("库存不足：" + snack.getName());
            }
            // 设置商品单价
            item.setPrice(snack.getPrice());
            // 累加总金额
            totalAmount = totalAmount.add(snack.getPrice().multiply(new BigDecimal(item.getQuantity())));
        }
        order.setTotalAmount(totalAmount);
        
        // 4. 保存订单
        save(order);

        // 5. 保存订单项并扣减库存
        for (OrderItem item : items) {
            item.setOrderId(order.getId());
            item.setCreatedAt(LocalDateTime.now());
            orderItemService.save(item);

            // 扣减库存
            Snack snack = snackService.getById(item.getSnackId());
            snack.setStock(snack.getStock() - item.getQuantity());
            snackService.updateById(snack);
        }
    }

    @Override
    public Page<Order> getMyOrders(String username, Integer status, Page<Order> page) {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        return baseMapper.getMyOrders(page, user.getId(), status);
    }

    // 添加一个工具方法来获取用户ID
    private Long getUserId(String username) {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        return user.getId();
    }

    @Override
    @Transactional
    public boolean deleteOrder(Long id) {
        // 获取订单信息
        Order order = this.getById(id);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 删除订单明细
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", id);
        orderItemService.remove(wrapper);
        
        // 删除订单
        return this.removeById(id);
    }
} 